package com.business.user.service.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.business.common.dto.R;
import com.business.common.enums.ErrorEnum;
import com.business.common.exception.CustomException;
import com.business.common.utils.StrKit;
import com.business.user.entity.UserDataQuantity;
import com.business.user.mapper.UserDataQuantityMapper;
import com.business.user.service.UserDataQuantityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * 用户数据统计表:业务接口实现类
 *
 * @author chenjiehong
 * @date 2019-11-29 14:28:27
 * @since 1.0
 */
@Service
public class UserDataQuantityServiceImpl implements UserDataQuantityService {

    @Autowired
    private UserDataQuantityMapper userDataQuantityMapper;


    @Override
    @Transactional
    public Integer addNumber(Integer userId, Integer quantity, String module) {
        if (StrKit.isBlank(module)) {
            throw new CustomException(ErrorEnum.PARAMS_LOSE, "module");
        }
        if (userDataQuantityMapper == null) {
            throw new CustomException(ErrorEnum.PARAMS_LOSE, "userId");
        }
        if (quantity == null) {
            quantity = 1;
        }
        Integer count = userDataQuantityMapper.selectCount(new EntityWrapper<UserDataQuantity>().eq("user_id", userId));
        if (count != null && count > 0) {
            userDataQuantityMapper.updateByField(userId, module + "_quantity", quantity);
        } else {
            userDataQuantityMapper.insertByField(userId, module + "_quantity", quantity);
        }
        if (module.indexOf("dynamic") == 0) {
            userDataQuantityMapper.updateByField(userId, "dynamic_quantity", quantity);
        }
        return count;
    }


    @Override
    public UserDataQuantity queryByUser(Integer userId) {
        return userDataQuantityMapper.selectById(userId);
    }

}